package br.com.manutencao.repositories;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

import javax.faces.model.SelectItem;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;

import br.com.manutencao.entities.Setor;

public class SetorRepository implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private EntityManager em;
	
	public SetorRepository(){
		em = Persistence.createEntityManagerFactory("jsf").createEntityManager();
	}

	public void adiciona(Setor setor) {
		em.getTransaction().begin();
		em.persist(setor);
		em.getTransaction().commit();
	}
	
	public void altera(Setor setor){
		em.getTransaction().begin();
		em.merge(setor);
		em.getTransaction().commit();
	}
	
	public void delete(Setor setor){
		em.getTransaction().begin();
		em.remove(setor);
		em.getTransaction().commit();
	}
	
	@SuppressWarnings("all")
	public Collection<Setor> buscaTodos(){
		Collection<Setor> setores = new ArrayList<Setor>();
		
		em.getTransaction().begin();
		Query query = em.createNamedQuery("Setor.findAll");
		setores = query.getResultList();
		em.getTransaction().commit();
		
		return setores;
	}
	
	public Setor buscaPorId(int id){
		em.getTransaction().begin();
		Setor setor = em.find(Setor.class, id);
		em.getTransaction().commit();
		
		return setor;
	}
	
	public Collection<SelectItem> buscaTodosNomes(){
		Collection<Setor> setores = buscaTodos();
		Collection<SelectItem> setorNomes = new ArrayList<SelectItem>();
		
		for (Setor setor : setores) {
			SelectItem selItem = new SelectItem(setor, setor.getNome());
			setorNomes.add(selItem);
		}
		
		return setorNomes;
	}
}
